package com.lsz.errorupload;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.provider.Settings;
import android.telephony.TelephonyManager;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by Administrator on 2016/11/14.
 */

public class ErrorUpload extends CordovaPlugin {

    CallbackContext callbackContext;

    private String purl;

    private Context ctx;

    @Override
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
        this.callbackContext = callbackContext;
        if (action.equals("start")) {
            ctx = cordova.getActivity();
            SharedPreferences sp = ctx.getSharedPreferences("errorLog", Context.MODE_PRIVATE);
            if (!sp.getBoolean("isUpload", true)) {
                JSONObject obj = args.getJSONObject(0);
                purl = obj.getString("prefixUrl");
                if(purl != null){
                    uploadError(sp);
                }
            }
        }
        return super.execute(action, args, callbackContext);
    }

    private void uploadError(SharedPreferences sp) {
        if (sp.getString("errorTitle", null) == null || sp.getString("errorMsg", null) == null || sp.getString("errorType", null) == null) {
            return;
        }
        try {
            JSONObject error = new JSONObject();
            error.put("errorTitle", sp.getString("errorTitle", null));
            error.put("errorMsg", sp.getString("errorMsg", null));
            error.put("errorType", sp.getString("errorType", null));
            TelephonyManager tm = (TelephonyManager) ctx.getSystemService(Context.TELEPHONY_SERVICE);
            error.put("phoneNo", tm.getLine1Number());
            //错误信息对象数组
            JSONArray arr = new JSONArray();
            arr.put(error);
            //请求参数arguments
            JSONObject arguments = new JSONObject();
            String uuid = Settings.Secure.getString(ctx.getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);
            arguments.put("mobileUUID", uuid);
            String osversion = android.os.Build.VERSION.RELEASE;
            arguments.put("mobileSysVersion", osversion);
            String model = android.os.Build.MODEL;
            arguments.put("mobileModel", model);
            PackageManager pm = ctx.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(ctx.getPackageName(), PackageManager.GET_CONFIGURATIONS);
            String versionName = pi.versionName;
            arguments.put("appVersion", versionName);
            String osType = "android";
            arguments.put("osType", osType);
            arguments.put("errorLog", arr);
            JSONObject requestParam = new JSONObject();
            requestParam.put("requestType", "7001");
            requestParam.put("arguments", arguments);
            startUpload(requestParam.toString(), sp);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void startUpload(final String s, final SharedPreferences sp) {
        new Thread() {
            @Override
            public void run() {
                try {
                    URL url = new URL(purl);
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setDoOutput(true);
                    connection.setDoInput(true);
                    connection.setUseCaches(false);
                    connection.setRequestProperty("Content-Type", "application/json");
                    connection.setRequestProperty("Charset", "UTF-8");
                    connection.setRequestMethod("POST");
                    connection.setRequestProperty("Content-Length", String.valueOf(s.getBytes().length));
                    connection.connect();
                    OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
                    writer.write(s);
                    writer.flush();
                    writer.close();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(
                            connection.getInputStream()));
                    String lines = reader.readLine();//读取请求结果
                    reader.close();
                    if (connection.getResponseCode() == 200) {
                        sp.edit().putBoolean("isUpload", true).commit();
                        callbackContext.success(lines);
                    } else {
                        callbackContext.error(lines);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
